﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace TaskFramework
{
    public class RoutingHelper
    {
        private readonly RouteRequestHandler _requestHandler;
        private readonly TaskEventHandler _eventHandler;
        private readonly TaskInfo _info;

        internal RoutingHelper(RouteRequestHandler requestHandler, TaskEventHandler eventHandler, TaskInfo info)
        {
            _requestHandler = requestHandler;
            _eventHandler = eventHandler;
            _info = info;
        }

        /// <summary>
        /// Routes a request back to the dispatcher.
        /// </summary>
        /// <param name="requestData"></param>
        public void RouteRequest(object requestData)
        {
            if (_requestHandler != null)
            {
                try
                {
                    _info.AddRoutedTaskId(_info.Task.TaskId);
                    _requestHandler.Invoke(_info.Task, requestData);
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e);
                }
            }
        }

        /// <summary>
        /// Routes a task back to the task pool. The task will be added to the task pool wait queue 
        /// when it has finished execution, and should therefore finish execution ASAP.
        /// </summary>
        /// <param name="task"></param>
        public void TransferToPool(Task task)
        {
            _info.TransferToPool = true;
        }

        /// <summary>
        /// Sends an event containing result data.
        /// </summary>
        /// <param name="result"></param>
        public void SendResult(object result)
        {
            if (_eventHandler != null)
            {
                try
                {
                    _eventHandler.Invoke(new TaskEvent(_info, result));
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e);
                }
            }
        }
    }
}
